import {parseHTML} from './parse-html.js'
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g
function generate(el){
    let  children = genChildren(el)// 获取了孩子节点
    let code = `_c("${el.tag}",${genProps(el.attrs)},${
        children ? children: ''
    })`
    return code
}
function genProps(attrs){
    let result = ''
    if(attrs && attrs.length){
        attrs.forEach(item => {
            let attr = item
            if(attr.name === 'style'){
                let obj = {}
                attr.value.split(';').forEach(attrItem => {
                    let [key, value] = attrItem.split(':')
                    obj[key] = value
                })
                attr.value = obj
            }
            result+=`${attr.name}:${JSON.stringify(attr.value)},`
        })
        
    }
    return result ? `{${result.slice(0,- 1)}}`: undefined
}
function gen(node){
    if(node.type === 1){
        return generate(node)
    }else{
        let text = node.text
        let tokens = []
        let match,index
        let lastIndex = defaultTagRE.lastIndex = 0
        while (match = defaultTagRE.exec(text)) {
            index = match.index
            if(index > lastIndex){
                tokens.push(JSON.stringify(text.slice(0,index)))
            }
            tokens.push(`_s(${match[1].trim()})`)
            lastIndex = index + match[0].length
        }

        if(lastIndex < text.length){
            tokens.push(JSON.stringify(text.slice(lastIndex)))
        }
        return `_v(${tokens.join('+')})`
    }
}

function genChildren(el){
    let children = el.children
    if(children && children.length){
        return `${children.map(c => gen(c)).join(',')}`
        
    }else{
        return false
    }
}
// ast语法树 是用对象来描述原生语法的，虚拟dom 用对象来描述dom节点的
export function compileToFunction(template){
    // 1.解析html字符串 将html字符串 => ast语法树
    let root = parseHTML(template)
    console.log(root,'root')
    // 2.将html字符串 => render函数 就是字符串拼接（模板引擎）
    let code = generate(root)
    console.log(code,'code')
    let renderFn = new Function(`with(this){return ${code}}`)
    console.log(renderFn,'renderFn')
    return renderFn
}